import { _decorator, Animation, Camera, Collider2D, Component, Contact2DType, EPhysics2DDrawFlags, find, IPhysics2DContact, log, Node, PhysicsSystem2D, tween, UITransform, Vec3, view } from 'cc';
import { GameManager } from './GameManager';
import { AudioManager } from './tool/AudioManager';
import { regainHP } from './tool/regainHP';
import { GlobalEvent } from './tool/GlobalEventManager';
import { enemy } from './enemy';
import { diren } from './diren';
const { ccclass, property } = _decorator;

@ccclass('PlayerManager')
export class PlayerManager extends Component {

    private isMoveing: boolean = false; // 核心：一个简单的标志位
    private isAttacking: boolean = false;
    //移动方向
    private moveDirection: Vec3 = new Vec3(0,0,0);
    //移动速度
    private moveSpeed: number = 110;

     //保存动画组件
    private _animation: Animation | null = null;

    //获取回血的节点
    @property(Node)
    targetNode: Node = null!;

    //碰撞回调
    private attackCollider: Collider2D = null;
    private isAttsacking: boolean = false;
    
    onLoad() {
        // 获取Animation组件
        this._animation = this.node.getComponent(Animation);

        // PhysicsSystem2D.instance.debugDrawFlags = EPhysics2DDrawFlags.All;
        // 获取玩家身上的碰撞体组件
        this.attackCollider = this.getComponent(Collider2D);
        
        if (this.attackCollider) {
            // 监听碰撞事件
            this.attackCollider.on(Contact2DType.BEGIN_CONTACT, this.onAttackHit, this);
            // 开始时不启用碰撞检测
            this.attackCollider.enabled = false;
        }
    }

    public kan(arg: number) {
        this.isAttsacking=true
         if (this.attackCollider) {
            this.attackCollider.enabled = true;
        }
    }
    public kanEnd(arg: number) {
        this.isAttsacking=false
         if (this.attackCollider) {
            this.attackCollider.enabled = false;
        }
    }
    // 碰撞检测：刀碰到敌人
    private onAttackHit(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if(!this.isAttsacking) return
        // console.log(`💥 击中敌人: ${contact}`,selfCollider.node.name);
        // if(selfCollider.node.name =='body'){
        //     GlobalEvent.emit('hitEnemy', 1);
        // }
        otherCollider.getComponent(diren).hurt(1);
        AudioManager.instance.playSFX('sound/chang');
    }

    start() {
     
    }

    toAttack(event: Event, customEventData: string) {
        if(GameManager.instance.getGameStatus() != 1) return;

        let clipName: string | null = null;
        const clips = this._animation.clips;
        // 遍历所有剪辑，检查哪个正在播放
        for (const clip of clips) {
            const state = this._animation.getState(clip.name);
            if (state && state.isPlaying) {
                clipName = clip.name;
            }
        }
        if(clipName == 'run' || clipName == 'zhan'){
            this.isAttacking = false;
        }



        if(this.isAttacking) return;
        this.isAttacking = true;
     
        let arr=['gong1','gong2','gong3'];
        if(customEventData == '1'){
            const randomItem = arr[Math.floor(Math.random() * arr.length)];
            if (this._animation && this._animation.clips.some(clip => clip.name === randomItem)) {
                 this._animation.on(Animation.EventType.FINISHED, () => {
                   if (!this.isMoveing) {
                        this._animation.play('zhan');
                    }else{
                        this._animation.play('run');
                    }
                    this.isAttacking = false;
                });
                // this._animation!.on(Animation.EventType.STOP, () => {
                //     this.isAttacking = false;
                // }, this);
                this._animation.play(randomItem);
            }
        }
        if(customEventData == '2'){
            let shu=this.targetNode.getComponent(regainHP).isCounting;
            if(shu){
                this.isAttacking = false;
                return;
            }
           this.targetNode.getComponent(regainHP).startCountdown();

            const state = this._animation.getState('gongchang');
            if (state) {
                state.speed = 0.3; 
            }

            this._animation.on(Animation.EventType.FINISHED, () => {
                if (!this.isMoveing) {
                    this._animation.play('zhan');
                }else{
                    this._animation.play('run');
                }
                this.isAttacking = false;
            });
            // this._animation!.on(Animation.EventType.STOP, () => {
            //     this.isAttacking = false;
            // }, this);
            this._animation.play('gongchang');
        }
    }





    toMove(direction: Vec3) {
        this.moveDirection = direction;
        if (this.isMoveing) return;
        this.isMoveing = true;

        if (this._animation && this._animation.clips.some(clip => clip.name === 'run')) {
            this._animation.play('run');
        }
    }
    endMove() {
        if (!this.isMoveing) return;
        this.moveDirection.x=0
        this.moveDirection.y=0
        this.isMoveing = false;
        if (this._animation && this._animation.clips.some(clip => clip.name === 'zhan')) {
            this._animation.play('zhan');
        }
        
    }
    //动起来
    move(deltaTime: number) {
        if(GameManager.instance.getGameStatus() != 1) return;
        if(!this.isMoveing) return;
         //根据方向 动起来
        if(this.moveDirection.x!=0){
            let num=0
            if(this.moveDirection.x > 0){
                num=1
            }else{
                num=-1
            }

            //改变缩放方向
            this.node.setScale(this.node.scale.y * num,this.node.scale.y,1);

           //获取距离边缘的距离
            const distances = this.getDistanceToEdge();
            if (distances) {
                // 判断是否接近边缘
                if (distances.left < 180 && num == -1) {
                     this.positionMove(num * this.moveSpeed*deltaTime)
                }else if (distances.right < 180  && num == 1) {
                    this.positionMove(num * this.moveSpeed*deltaTime)
                }else {
                     this.node.x= this.node.x + num * this.moveSpeed*deltaTime;
                }
            }
        }
        if(this.moveDirection.y!=0){
          //  this.node.y= this.node.y+this.moveDirection.y * this.moveSpeed*deltaTime;
        }
    }

    //相机移动,
    positionMove(deltaX: number) {
    //    log('相机移动',deltaX)
         const parent = this.node.parent;
        let x=parent.position.x + deltaX

        if(x<=0){
            x=0
        }
        if(x>=1300){
            x=1300
        }

        if (parent) {
            const newParentPos = new Vec3(
                x,
                parent.position.y,
                parent.position.z
            );
            parent.position = newParentPos;
        }
    }


      getDistanceToEdge() {
        // 获取屏幕尺寸
        const screenSize = view.getVisibleSize();
        
        // 获取UI变换组件
        const uiTransform = this.node.getComponent(UITransform);
        
        // 获取节点位置（相对于屏幕中心）
        const nodePos = this.node.position;
        
        // 计算到各边缘的距离
        const distanceToLeft = screenSize.width / 2 + nodePos.x;
        const distanceToRight = screenSize.width / 2 - nodePos.x;
        const distanceToBottom = screenSize.height / 2 + nodePos.y;
        const distanceToTop = screenSize.height / 2 - nodePos.y;
        
        return {
            left: distanceToLeft,
            right: distanceToRight,
            bottom: distanceToBottom,
            top: distanceToTop
        };
    }

    update(deltaTime: number) {
       this.move(deltaTime);
    }
}


